function mylog(msg){
    console.log("[NextPlease] "+msg)
}

/* we can't use localStorage, so i sending message to bakground html */
var site_profiles = null;
var cur_profile = null;

chrome.extension.sendRequest({method: "getValue", key: "site_profiles"}, function(response) {
    try{
        site_profiles = JSON.parse(response.value)
    }catch(e){
        mylog("Error:"+e)
    }
    mylog("profiles:")
    console.log(site_profiles);
    cur_profile = getCurrentProfile()
    mylog("cur profile:")
    console.log(cur_profile);
});

function getCurrentProfile(){
    if(!site_profiles) return null;

    var  URL = window.location+""
    URL = URL.toLowerCase();
    
    try{
    
    for(i=0;i<site_profiles.length;i++){
        matchStr = site_profiles[i].url_match.toLowerCase()
        if(URL.indexOf(matchStr)>=0) return site_profiles[i]
    }
    
    mylog("no matching profile")
    
    }catch(e){
        mylog("getCurrentProfile Error:"+e)
    }
    
    return null;
}

function elementMatch(elem, profile, prev){
    var text = profile.next_elem_text; 
    var title = profile.next_elem_title;
    if(prev){
        text = profile.prev_elem_text; 
        title = profile.prev_elem_title; 
    }

    if(elem.text() != text) return false
    if(title){
        
        var re = new RegExp(title);
        if(!elem.attr('title').match(re)) return false
    }
    return true
}

function hookKeys(){

$(document).keydown(function(e){

    mylog("keydown "+e.keyCode)
    
    var prev = null;
    if(e.keyCode == 37) prev = true
    if(e.keyCode == 39) prev = false
    
    if(prev==null) return true;
    
    if(!cur_profile) return true

    try{
    
    $("a").each(function(i,elem){
        var e = $(elem)
        if(elementMatch(e, cur_profile, prev)){
            var newlocation = $(elem).attr('href')
            console.log("clicking "+newlocation)
            window.location = newlocation
            return false
        }
    });

    mylog("no match")
    
    }catch(e){
        mylog("Error: "+e)
    }

    return true;
});

}

hookKeys()